package com.company.ems.filter;

import com.company.ems.model.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


@WebFilter(urlPatterns = "/*", filterName = "AuthenticationFilter")
public class AuthenticationFilter implements Filter {
    // 无需登录的路径
    private static final String[] EXCLUDE_PATHS = {
            "/login.jsp",
            "/LoginServlet",
            "/css/",
            "/js/"
    };

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        String requestURI = req.getRequestURI();

        boolean isExclude = false;
        for (String path : EXCLUDE_PATHS) {
            if (requestURI.startsWith(req.getContextPath() + path) || requestURI.equals(req.getContextPath() + "/")) {
                isExclude = true;
                break;
            }
        }
        if (isExclude) {
            chain.doFilter(request, response);
            return;
        }


        HttpSession session = req.getSession();
        User loginUser = (User) session.getAttribute("loginUser");
        if (loginUser == null) {
            // 未登录，重定向到登录页
            resp.sendRedirect(req.getContextPath() + "/login.jsp");
            return;
        }

        // 3. 已登录，放行
        chain.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {}
    @Override
    public void destroy() {}
}